package neu.soft.facade;

import com.alibaba.fastjson.JSON;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import neu.soft.constant.PurchaseOrderType;
import neu.soft.entity.*;
import neu.soft.exception.AppException;
import neu.soft.exception.AppExceptionCodeMsg;
import neu.soft.feignclient.WarehouseFeignClient;
import neu.soft.service.GoodsService;
import neu.soft.service.SupplyService;
import neu.soft.service.VendorService;
import neu.soft.service.WarehouseService;
import neu.soft.util.TypeConvert;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
@Slf4j
public class SupplyHandler {

    @Autowired
    SupplyService supplyService;

    @Autowired
    WarehouseService warehouseService;

    @Autowired
    WarehouseFeignClient warehouseFeignClient;

    @Autowired
    GoodsService goodsService;

    @Autowired
    VendorService vendorService;

    //缺货所需的购货方法
    @SneakyThrows
    public OperationPurchaseOrder consumeSupplyMsg(Map<String, Object> receiveMap) {

        if (receiveMap == null || receiveMap.size() == 0) {
            throw new AppException(AppExceptionCodeMsg.REQUEST_PARAM_EMPTY);
        }
        String orderId = (String) receiveMap.get("oid");
        //转换为NormalOrderInfo类型的集合
        String jsonObject = JSON.toJSONString(receiveMap.get("shopping"));
        List<NormalOrderInfo> receiveList = TypeConvert.jsonArrayToList(jsonObject, NormalOrderInfo.class);
        //生成购货单商品信息
        List<GoodInfo> goodInfoReceiveList = receiveList.stream()
                .map(TypeConvert::goodInfoConverter)
                .collect(Collectors.toList());
        //缺货检查
        //获取商品代码列表
        List<String> goodIdList = receiveList.stream()
                .map(NormalOrderInfo::getShoppingCode)
                .collect(Collectors.toList());
        //获取库房预警值
        OperationWarehouse operationWarehouse = warehouseService.findById(1);
        int alertValue = operationWarehouse.getAlertValue();
//        获取库存里现有的库存量
        List<Inventory> inventoryList = warehouseFeignClient.queryInventoryByCodeList(goodIdList);
        if (inventoryList.size() == 1 && "-1".equals(inventoryList.get(0).getCode())) {
            throw new AppException(AppExceptionCodeMsg.QUERY_FAIL);
        }
//        缺货检查，如果通过则返回true
        boolean isTrue = supplyService.checkShortage(receiveList, inventoryList, alertValue);
        if (!isTrue) {
            throw new AppException(AppExceptionCodeMsg.CHECK_FAIL);
        }
        //获取商品信息里的商品，默认一个购货单只能购买同一供应商的商品，获取商品信息用于获取供应商信息
        Good good = goodsService.findById(goodInfoReceiveList.get(0).getGoodId());
        //获取供应商名称，也是作为一个主键
        String vendorName = good.getVendor();
        //通过名称查询供应商
        Vendor vendor = vendorService.findByName(vendorName);
        //获取总金额
        BigDecimal totalPrice = supplyService.getTotalPrice(goodInfoReceiveList);
        //获取缺货购货单类型
        String purchaseOrderType = PurchaseOrderType.OUT_OF_STOCK_PURCHASE.getCode();
        //获取初步购货单
        OperationPurchaseOrder operationPurchaseOrder = supplyService.generatePurchaseOrder(orderId, goodInfoReceiveList, vendor, totalPrice, purchaseOrderType);//生成购货单
        //购货登记
        supplyService.addPurchaseOrder(operationPurchaseOrder);
        //完善购货单
        operationPurchaseOrder = supplyService.finishPurchaseOrder(operationPurchaseOrder);
        List<GoodInfo> goodInfoList = operationPurchaseOrder.getGoodInfoList();
        //批量插入购货单的商品信息
        supplyService.batchInsertGoodInfo(goodInfoList);
        String type = TypeConvert.enumToString(PurchaseOrderType.class,operationPurchaseOrder.getPurchaseType());
        operationPurchaseOrder.setPurchaseType(type);
        //调用财务中心服务，传递购货单
        return operationPurchaseOrder;
    }

    //从新供应商购货
    @SneakyThrows
    public OperationPurchaseOrder purchaseOrderFromVendor(Map<String, Object> map) {
        String vendorName = (String) map.get("vendor");
        Vendor vendor = vendorService.findByName(vendorName);
        //vendorService.addVendor(vendor);添加新供应商信息，可能在前端调用，先放这里
        String jsonObject = JSON.toJSONString(map.get("goodInfoList"));
        List<GoodInfo> goodInfoList = TypeConvert.jsonArrayToList(jsonObject, GoodInfo.class);
        //计算总金额
        BigDecimal totalPrice = supplyService.getTotalPrice(goodInfoList);
        //获取购货单类型,从新供应商处购货
        String purchaseOrderType = PurchaseOrderType.NEW_VENDOR_PURCHASE.getCode();
        //生成初步购货单
        OperationPurchaseOrder operationPurchaseOrder = supplyService.generatePurchaseOrder(null, goodInfoList, vendor, totalPrice, purchaseOrderType);
        //添加购货单
        supplyService.addPurchaseOrder(operationPurchaseOrder);
        //完善购货单中的商品信息
        supplyService.finishPurchaseOrder(operationPurchaseOrder);
        //批量插入购货单的商品信息
        List<GoodInfo> goodInfo = operationPurchaseOrder.getGoodInfoList();
        supplyService.batchInsertGoodInfo(goodInfo);
        return operationPurchaseOrder;
    }

}
